package org.example.chat.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import lombok.extern.slf4j.Slf4j;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.apache.commons.lang3.StringUtils;
import org.example.chat.security.entity.LoginUser;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.util.HashMap;
import java.util.Map;

/**
 * @author cheval
 */
@Slf4j
public class CommonUtils {
    public static String getServerIp() {
        String ip = null;
        try {
            ip = InetAddress.getLocalHost().getHostAddress();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ip;
    }

    public static LoginUser getLoginUserInfo() {
        return  (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    }

    /**
     * 生成二维码到文件
     * @param content
     * @param width
     * @param height
     * @param file
     */
    public static void genQRCodeToFile(String content, int width, int height, File file) {
       if (StringUtils.isBlank(content)) {
           return;
       }
       content = content.trim();
       if (width == 0) {
           width = 300;
       }
       if (height == 0) {
           height = 300;
       }
       if (file == null) {
           return;
       }
       if (file.isDirectory()) {
           return;
       }

        BufferedImage image = createBufferImage(content, width, height);
        try {
            ImageIO.write(image, "png", file);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 生成Base64格式的二维码
     * @param content
     * @param width
     * @param height
     * @return
     */
    public static String genCodeToBase64String(String content, int width, int height) {
        if (StringUtils.isBlank(content)) {
            return null;
        }
        content = content.trim();
        if (width == 0) {
            width = 300;
        }
        if (height == 0) {
            height = 300;
        }
        BufferedImage image = createBufferImage(content, width, height);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "png", bos);
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] bytes = bos.toByteArray();
        BASE64Encoder encoder = new BASE64Encoder();
        String base64Image = encoder.encode(bytes);
        return base64Image;
    }


    /** 二维码前景色 */
    private static final int FRONT_COLOR = 0x000000;
    /** 二维码背景色 */
    private static final int BACKGROUND_COLOR = 0xFFFFFF;

    /**
     * 生成二维码图像
     * @return
     */
    private static BufferedImage createBufferImage(String content, int width, int height) {
        // 1. 设置二维码参数
        Map<EncodeHintType, Object> hints = new HashMap<>();
        // 字符编码
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        // 误差校正
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        // 二维码边距， 单位像素， 值越小， 二维码距离四周越近
        hints.put(EncodeHintType.MARGIN, 1);

        // 2. 生成二维码
        MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
        BitMatrix bitMatrix = null;
        try {
            bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints);
        } catch (WriterException e) {
            e.printStackTrace();
        }
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        if (bitMatrix != null) {
            for (int i = 0; i < width; i++) {
                for (int j = 0; j < height; j++) {
                    image.setRGB(i , j, bitMatrix.get(i, j) ? FRONT_COLOR : BACKGROUND_COLOR);
                }
            }
        }
        return image;
    }


    /**
     * 为图片添加水印
     * @param srcImagePath
     * @param targetImagePath
     * @param waterText
     * @return
     */
    public static boolean addWaterForImage(String srcImagePath, String targetImagePath, String waterText) {
        float alpha = 0.2F;
        double degree = 330;
        String font = "隶书";
        int fontStyle = Font.ITALIC;
        int fontSize = 150;
        Color fontColor = Color.DARK_GRAY;
        int xInterval = 600;
        int yInterval = 150;
        FileOutputStream outputStream = null;
        try {
            File srcImageFile = new File(srcImagePath);
            if (!srcImageFile.exists()) {
                // 源文件不存在
                System.out.println("目标图片文件不存在");
                return false;
            }
            Image srcImage = ImageIO.read(srcImageFile);
            BufferedImage srcBufferImage = new BufferedImage(srcImage.getWidth(null), srcImage.getHeight(null), BufferedImage.TYPE_INT_RGB);
            Graphics2D srcImageGraphics = srcBufferImage.createGraphics();
            srcImageGraphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            srcImageGraphics.drawImage(srcImage.getScaledInstance(srcImage.getWidth(null), srcImage.getHeight(null), Image.SCALE_SMOOTH), 0, 0, null);

            int imageHeight = srcBufferImage.getHeight();
            int imageWidth = srcBufferImage.getWidth();

//            AlphaComposite alphaComposite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha);
//            srcImageGraphics.setComposite(alphaComposite);
//            srcImageGraphics.setFont(new Font(font, Font.ITALIC, 40));
//            srcImageGraphics.setColor(fontColor);

            srcImageGraphics.rotate(Math.toRadians(degree), (double) imageWidth / 2, (double) imageHeight / 2);
            srcImageGraphics.setFont(new Font(font, fontStyle, fontSize));
            srcImageGraphics.drawString(waterText, (imageWidth - srcImageGraphics.getFontMetrics(srcImageGraphics.getFont()).charsWidth(waterText.toCharArray(), 0, waterText.length())) / 2, imageHeight / 2);
            srcImageGraphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
            srcImageGraphics.dispose();

            outputStream = new FileOutputStream(targetImagePath);
            ImageIO.write(srcBufferImage, "JPG", outputStream);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (Exception e) {
                System.out.println("文件流关闭异常");
            }
        }
    }

    /**
     * 汉字转拼音，如果非汉字则保持原文本输出
     * @param chinese
     * @return
     */
    public static String convertPinyin(String chinese) {
        // 设置不带声调
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        // 转化
        try {
            // retain: true 当无法转化为拼音时，保持原文本输出
            String pinyin = PinyinHelper.toHanYuPinyinString(chinese, format, "", true);
            return pinyin;
        } catch (BadHanyuPinyinOutputFormatCombination e) {
            log.info("汉字转拼音异常： {}", e.getMessage());
            return null;
        }
    }

    public static void main(String[] args) {
//        String qrcode = CommonUtils.genCodeToBase64String("hello", 300, 300);
//        System.out.println(qrcode);


//        addWaterForImage("C:\\Users\\cheva\\Desktop\\file\\1.jpg", "C:\\Users\\cheva\\Desktop\\file\\2.jpg", "杨旭伟");

        String chinese = "31231";
        try {
            HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
            format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
            String s = PinyinHelper.toHanYuPinyinString(chinese, format, "", true);
            log.info(s);
        } catch (BadHanyuPinyinOutputFormatCombination badHanyuPinyinOutputFormatCombination) {
            badHanyuPinyinOutputFormatCombination.printStackTrace();
        }

    }
}
